import { FC, PropsWithChildren, ReactNode, Suspense, useEffect, useMemo, useState } from 'react';
import { EditOutlined, LogoutOutlined } from '@ant-design/icons';
import { MenuDataItem, PageContainer, ProLayout, useToken } from '@ant-design/pro-components';
import { Dropdown, Spin } from 'antd';
import { Outlet, useLocation, useMatches } from 'react-router-dom';
import { routeUrlMap } from '@/router';
import { RouteKey } from '@/router/constants/router';
import useFcNavigate from '@/router/hooks/useFcNavigate';
import { menuStore, userStore } from '@/stores';

const formatMenusToMenuMap = (menus: MenuDataItem[]) => {
  const map: {
    [key: string]: {
      openKeys?: string[];
      selectedKeys?: string[];
    };
  } = {};
  const loop = (nodes: MenuDataItem[], parent?: string[]) => {
    nodes.forEach((node: MenuDataItem) => {
      if (routeUrlMap?.[node?.key]) {
        map[routeUrlMap[node.key]] = {
          selectedKeys: [node.key],
          openKeys: node?.children?.length ? parent.concat([node.key]) : parent,
        };

        if (!!node?.children?.length) {
          loop(node?.children, parent.concat([node.key]));
        }
      }
    });
  };

  loop(menus, []);

  return map;
};

const Platform: FC = (props: PropsWithChildren) => {
  const location = useLocation();
  const { menus } = menuStore;
  const { info } = userStore;

  const { token } = useToken();
  const navigate = useFcNavigate();
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const matches = useMatches();

  const menuMap = useMemo(() => formatMenusToMenuMap(menus), [menus]);

  useEffect(() => {
    const lastMatch = matches?.[matches.length - 1];

    if (lastMatch) {
      const { params, pathname } = lastMatch;

      if (menuMap?.[pathname]) {
        // eslint-disable-next-line @typescript-eslint/no-shadow
        const { openKeys, selectedKeys } = menuMap?.[pathname];

        setOpenKeys(openKeys);
        setSelectedKeys(selectedKeys);
      } else {
        const paramKeys = Object.keys(params);

        let matchPathname: string;

        if (paramKeys?.length) {
          const regex = /:/gi;

          Object.keys(menuMap).some((url: string) => {
            if (url?.match(regex)?.length !== paramKeys.length) {
              return false;
            }

            let composePathname: string;

            paramKeys.forEach((key: string) => {
              composePathname = pathname.replace(`:${key}`, params[key].toString());
            });

            if (pathname === composePathname) {
              matchPathname = url;

              return true;
            } else {
              return false;
            }
          });
        }

        if (matchPathname && menuMap?.[matchPathname]) {
          // eslint-disable-next-line @typescript-eslint/no-shadow
          const { openKeys, selectedKeys } = menuMap?.[matchPathname];

          setOpenKeys(openKeys);
          setSelectedKeys(selectedKeys);
        }
      }
    }
  }, [menuMap, matches]);

  return (
    <ProLayout
      {...props}
      layout="mix"
      // logo={logoJpg}
      title="stratify量化"
      location={location}
      onMenuHeaderClick={() => {
        navigate(RouteKey.Home);
      }}
      menuDataRender={() => menus}
      menuItemRender={(item: MenuDataItem, dom: ReactNode) => {
        return (
          <div onClick={() => navigate(item?.key || '')}>
            <a
              href={item.url}
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              {dom}
            </a>
          </div>
        );
      }}
      menuProps={{
        openKeys,
        selectedKeys,
        // eslint-disable-next-line @typescript-eslint/no-shadow
        onSelect: ({ selectedKeys }) => {
          setSelectedKeys(selectedKeys);
        },
        // eslint-disable-next-line @typescript-eslint/no-shadow
        onOpenChange: (openKeys) => {
          setOpenKeys(openKeys);
        },
      }}
      avatarProps={{
        src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
        size: 'small',
        title: info?.nickName,
        render: (_, dom) => {
          return (
            <Dropdown
              menu={{
                items: [
                  {
                    key: 'forget',
                    label: '重置密码',
                    icon: <EditOutlined />,
                    onClick: () => {},
                  },
                  {
                    key: 'logout',
                    label: '退出登录',
                    icon: <LogoutOutlined />,
                    onClick: () => {},
                  },
                ],
              }}
            >
              {dom}
            </Dropdown>
          );
        },
      }}
      token={{
        sider: {
          colorMenuBackground: '#fff',
          colorTextMenu: '#595959',
          colorTextMenuSelected: token.colorPrimaryText,
          colorBgMenuItemSelected: token.colorPrimaryBg,
          colorTextMenuItemHover: token.colorPrimaryTextHover,
        },
      }}
    >
      <PageContainer
        childrenContentStyle={{ padding: 0 }}
        // waterMarkProps={{
        //   content: `${info?.nickName}  ${info?.mobile?.slice(7, 11)}`,
        //   rotate: -30,
        // }}
        // className='px-4'
        // pageHeaderRender={false}
        // breadcrumbRender={false}
      >
        <Suspense
          fallback={
            <div className="w-full h-full flex justify-center items-center">
              <Spin delay={300} />
            </div>
          }
        >
          <Outlet />
        </Suspense>
      </PageContainer>
    </ProLayout>
  );
};

export default Platform;
